/*
 * circularbuffer.cpp
 *
 *  Created on: Jun 24, 2009
 *      Author: z1083248
 */
#include "gen_circularbuffer.h"
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>

circularBufferT * _buffer;

void gen_initBuffer(circularBufferT * const buffer)
{
   _buffer = buffer;
}

void gen_addToBuffer(BUFF_DATA inData)
{
   if (_buffer->isEmpty)
   {
      _buffer->isEmpty = false;
   }
   else
   {
      // Increment end pointer to point to new data.
      _buffer->ptr_end = _buffer->data +
            (((_buffer->ptr_end - _buffer->data) + 1) % _buffer->size);

      if (_buffer->ptr_end == _buffer->ptr_first)
      {
         // increment first pointer (points to oldest data), if buffer is full
         // (no circular) and overwriting old data.
         _buffer->ptr_first = _buffer->data +
               (((_buffer->ptr_first - _buffer->data) + 1) % _buffer->size);
      }
      _buffer->fifo_read_index = _buffer->ptr_end;
   }
   *(_buffer->ptr_end) = inData;

}

int gen_readNext(BUFF_DATA * const outData)
{
   if (_buffer->isEmpty || _buffer->fifo_read_index == NULL)
   {
      return -1;
   }

   *outData = *(_buffer->fifo_read_index);

   // increment fifo_read_index pointer.
   // ensure we do not go outside of our buffer.
   if (_buffer->fifo_read_index == _buffer->ptr_first)
   {
      _buffer->fifo_read_index = 0;
   }
   else
   {
      if (_buffer->fifo_read_index - _buffer->data == 0)
      {
         _buffer->fifo_read_index += (_buffer->size - 1);
      }
      else
      {
         _buffer->fifo_read_index = _buffer->data +
                  ((_buffer->fifo_read_index - _buffer->data) - 1);
      }
   }

   return 0;
}

void gen_printLifoBuffer()
{
   BUFF_DATA outData = 0.0f;
   puts("LIFO Circular Buffer:");
   while (gen_readNext(&outData) == 0)
   {
      printf("%f\n", outData);
   }
   puts("\n");
}

void gen_dispose()
{

}
